import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as API from '../api/http'


let initialState = {
    list: [],
    newlist: []
}

const todosSlice = createSlice({
    name: "todos",
    initialState,
    reducers: {
        getlist(store, action) {
            store.list = action.payload
        },
        addlist(store: any, action) {
            store.list.push(action.payload)
        },
        newgetlist(store, action) {
            store.newlist = action.payload
        },
        dellist(store: any, action) {
            store.newlist = store.newlist.filter((item: any) => {
                return item.id != action.payload
            })
        },
        updatelist(store: any, action) {
            let lists = store.newlist.findIndex((item: any) => {
                return item.id == action.payload.id
            })
            store.newlist[lists] = action.payload
        },
    },
});

export const actionfn = todosSlice.actions;
export default todosSlice.reducer;

export let action_getlist = createAsyncThunk('action_getlist',
    async (_, store) => {
        let res = await API.getlist()

        store.dispatch(actionfn.getlist(res))
    })

export let action_addlist = createAsyncThunk('action_addlist',
    async (params, store) => {
        let res = await API.addlist(params)

        store.dispatch(actionfn.addlist(res))
    })


export let action_newgetlist = createAsyncThunk('action_newgetlist',
    async (_, store) => {
        let res = await API.newgetlist()

        store.dispatch(actionfn.newgetlist(res))
    })

export let action_dellist = createAsyncThunk('action_dellist',
    async (id, store) => {
        await API.dellist(id)

        store.dispatch(actionfn.dellist(id))
    })
export let action_update = createAsyncThunk('action_update',
    async (params, store) => {
        let res = await API.updatelist(params)

        store.dispatch(actionfn.updatelist(res))
    })

